import * as fs from 'fs';
import pool, { query } from './utils/database';

const backupDir: string = (process.env.ENV === "local") ? "./backup" : "/tmp"
const isDebug: boolean = process.env.DEBUG === "true";

export async function handler(sql: string, values?: any[]): Promise<void> {
  console.log("handler triggered!");
  if (isDebug) {
    if (!fs.existsSync(backupDir)) {
      fs.mkdirSync(backupDir);
    }
    const fileName: string = `${backupDir}/sql_statements.sql`;
    fs.appendFileSync(fileName, Date.now().toString() + ":\t" + sql + "\t" + JSON.stringify(values ?? []) + "\n",);
    console.log(`SQL statement has been backed up to ${fileName}`);
  }
  const records = await query(sql, values);
  console.log(records);
}

// 确保在程序退出时结束连接池中的所有连接
process.on('exit', () => {
  pool.end((err) => {
    if (err) {
      console.error('关闭数据库连接时发生错误:', err);
    } else {
      console.log('数据库连接已关闭');
    }
  });
});